<?php
/**
 * User: webrx
 * Date: 2017/1/4 13:42
 *  Ver: 1.0
 * Info:
 */
date_default_timezone_set('PRC');
$dsn = 'mysql:host=localhost;dbname=zgdb;port=3306;charset=utf8';
// $dsn = 'mysql:host=jm1n557c.2316lan.dnstoo.com;dbname=a0817225445;port=3306;charset=utf8';
$user = 'root';
// $user = 'a0817225445_f';
//$pass = '79424ed2';
// $pass = 'hw130145';
$opt = [19 => 2, 1002 => 'set names utf8'];
$pass = '';
try {
    $db = new pdo($dsn, $user, $pass, $opt);
} catch (exception $e) {
    exit('MySQL Server Connect Fail...');
}

function save($tn, $data) {
    global $db;
    foreach ($data as $k => $v) {
        $kk[] = $k;
        $vv[] = ':' . $k;
    }
    $kk = implode(',', $kk);
    $vv = implode(',', $vv);
    $stmt = $db->prepare("insert into $tn($kk) values($vv)");
    $stmt->execute($data);
    $stmt->closeCursor();
}


function saveok($tn, $data) {
    global $db;
    foreach ($data as $k => $v) {
        $kk[] = $k;
        $vv[] = ':' . $k;
    }
    $kk = implode(',', $kk);
    $vv = implode(',', $vv);
    $stmt = $db->prepare("insert into $tn($kk) values($vv)");
    $stmt->execute($data);
    $stmt->closeCursor();
    return $db->lastInsertId();
}

function countinfo($tn) {
    global $db;
    $stmt = $db->prepare("select * from $tn");
    $stmt->execute();
    $stmt->bindColumn(1, $c);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return $c;
}

function js($today, $c) {
    $f = $today - $c;
    if ($f > 0) {
        return true;
    } else {
        return false;
    }
}


function jpage($tn, $ps = 10, $f = '*', $w = '1=1', $o = '', $tp = '') {
    global $db;
    $stmt = $db->prepare("select count(*) from $tn where $w");
    $stmt->execute();
    $stmt->bindColumn(1, $recordcount);
    $stmt->fetch(PDO::FETCH_BOUND);
    $stmt->closeCursor();
    $pagecount = ceil($recordcount / $ps);
    $p = isset($_GET['p']) ? $_GET['p'] : 1;
    if ($p < 1) $p = 1;
    if ($p > $pagecount) $p = $pagecount;
    $dd['recordcount'] = $recordcount;
    $dd['pagecount'] = $pagecount;
    $dd['p'] = $p;

    //求这一页的数据
    $stmt = $db->prepare("select $f from $tn where $w $o limit ?,?");
    $start = $p * $ps - $ps;
    $stmt->bindParam(1, $start, PDO::PARAM_INT);
    $stmt->bindParam(2, $ps, PDO::PARAM_INT);
    $stmt->execute();
    $dd['rows'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    //实现百度分页效果
    $info = '<div class="page">';
    $ss = 1;
    $ee = 10;
    if ($p > 6) {
        $ss = $p - 5;
        $ee = $p + 4;
    }
    if ($ss > 1) $info .= sprintf('<a href="javascript:void(0)" pid="1">首页</a>', 1);
    if ($p > 1) $info .= sprintf('<a href="javascript:void(0)" pid="%d">上一页</a>', $p - 1);
    for ($i = $ss; $i <= $ee; $i++) {
        if ($i > $pagecount) break;
        if ($i == $p) {
            $info .= sprintf('<span>%d</span>', $i);
            continue;
        }
        $info .= sprintf('<a href="javascript:void(0)" pid="%d">%d</a>', $i, $i);
    }
    if ($p != $pagecount) $info .= sprintf('<a href="javascript:void(0)" pid="%d">下一页</a>', $p + 1);
    if ($p < $pagecount) $info .= sprintf('<a href="javascript:void(0)" pid="%d">尾页</a>', $pagecount);
    $info .= '</div>';
    $dd['info'] = $info;
    return $dd;
}

function page($tn, $ps = 10, $f = '*', $w = '1=1', $o = '', $tp = '') {
    global $db;
    $stmt = $db->prepare("select count(*) from $tn where $w");
    $stmt->execute();
    $stmt->bindColumn(1, $recordcount);
    //绑定一列到一个 PHP 变量
    $stmt->fetch(PDO::FETCH_BOUND);
    //以布尔值的形式返回结果，同时将获取的列值赋给bindParam()方法中指定的变量。
    $stmt->closeCursor();
    $pagecount = ceil($recordcount / $ps);//ceil() 函数向上舍入为最接近的整数
    $p = isset($_GET['p']) ? $_GET['p'] : 1;
    if ($p < 1) $p = 1;
    if ($p > $pagecount) $p = $pagecount;
    $dd['recordcount'] = $recordcount;
    $dd['pagecount'] = $pagecount;
    $dd['p'] = $p;

    //求这一页的数据
    $stmt = $db->prepare("select $f from $tn where $w $o limit ?,?");
    $start = $p * $ps - $ps;
    $stmt->bindParam(1, $start, PDO::PARAM_INT);
    $stmt->bindParam(2, $ps, PDO::PARAM_INT);
    $stmt->execute();
    $dd['rows'] = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmt->closeCursor();

    //实现百度分页效果
    $info = '<div class="page">';
    $ss = 1;
    $ee = 10;
    if ($p > 6) {
        $ss = $p - 5;
        $ee = $p + 4;
    }
    if ($ss > 1) $info .= sprintf('<a href="?%sp=%d">首页</a>', $tp, 1);
    if ($p > 1) $info .= sprintf('<a href="?%sp=%d">上一页</a>', $tp, $p - 1);
    for ($i = $ss; $i <= $ee; $i++) {
        if ($i > $pagecount) break;
        if ($i == $p) {
            $info .= sprintf('<span>%d</span>', $i);
            continue;
        }
        $info .= sprintf('<a href="?%sp=%d">%d</a>', $tp, $i, $i);
    }
    if ($p != $pagecount) $info .= sprintf('<a href="?%sp=%d">下一页</a>', $tp, $p + 1);
    if ($p < $pagecount) $info .= sprintf('<a href="?%sp=%d">尾页</a>', $tp, $pagecount);
    $info .= '</div>';
    $dd['info'] = $info;
    return $dd;
}

function page1($tn, $ps = 10, $f = '*', $w = '1=1', $o = '', $tp = '') {
    global $db;
    $stmt = $db->prepare("select count(*) from $tn where $w");
    $stmt->execute();
    $stmt->bindColumn(1, $recordcount);
    $stmt->fetch(PDO::FETCH_BOUND);
    $stmt->closeCursor();
    $pagecount = ceil($recordcount / $ps);
    $p = isset($_GET['pp']) ? $_GET['pp'] : 1;
    if ($p < 1) $p = 1;
    if ($p > $pagecount) $p = $pagecount;
    $dd['recordcount'] = $recordcount;
    $dd['pagecount'] = $pagecount;
    $dd['p'] = $p;

    //求这一页的数据
    $stmt = $db->prepare("select $f from $tn where $w $o limit ?,?");
    $start = $p * $ps - $ps;
    $stmt->bindParam(1, $start, PDO::PARAM_INT);
    $stmt->bindParam(2, $ps, PDO::PARAM_INT);
    $stmt->execute();
    $dd['rows'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();

    //实现百度分页效果
    $info = '<div class="page">';
    $ss = 1;
    $ee = 10;
    if ($p > 6) {
        $ss = $p - 5;
        $ee = $p + 4;
    }
    if ($ss > 1) $info .= sprintf('<a href="?pp=%d">首页</a>', 1);
    if ($p > 1) $info .= sprintf('<a href="?pp=%d">上一页</a>', $p - 1);
    for ($i = $ss; $i <= $ee; $i++) {
        if ($i > $pagecount) break;
        if ($i == $p) {
            $info .= sprintf('<span>%d</span>', $i);
            continue;
        }
        $info .= sprintf('<a href="?pp=%d">%d</a>', $i, $i);
    }
    if ($p != $pagecount) $info .= sprintf('<a href="?pp=%d">下一页</a>', $p + 1);
    if ($p < $pagecount) $info .= sprintf('<a href="?pp=%d">尾页</a>', $pagecount);
    $info .= '</div>';
    $dd['info'] = $info;
    return $dd;
}

function delete($tn, $id) {
    global $db;
    $pk = getpk($tn);
    $stmt = $db->prepare("delete from $tn where $pk=?");
    $stmt->execute([$id]);
    $stmt->closeCursor();
}


function deletepid($tn, $pk, $id) {
    global $db;
    $stmt = $db->prepare("delete from $tn where $pk=?");
    $stmt->execute([$id]);
    $stmt->closeCursor();
}

function deleteIn($tn, $pk, $id) {
    global $db;
    $stmt = $db->prepare("delete from $tn where $pk in ($id)");
    $stmt->execute([$id]);
    $stmt->closeCursor();
}

function maxs($tn, $f, $w) {
    global $db;
    $stmt = $db->prepare("select max($f) from $tn where $w");
    $stmt->execute();
    $stmt->bindColumn(1, $c);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return $c;
}

function counts($tn, $f, $w) {
    global $db;
    $stmt = $db->prepare("select count($f) from $tn where $w");
    $stmt->execute();
    $stmt->bindColumn(1, $c);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return $c;
}

function del($tn, $w = '1=1') {
    global $db;
    $stmt = $db->prepare("delete from $tn where $w");
    $stmt->execute();
    $stmt->closeCursor();
}

function update($tn, $data) {
    global $db;
    $pk = getpk($tn);
    if (empty($pk)) return;
    if (!array_key_exists($pk, $data)) return;//检查键名 是否存在于数组中：
    $id = $data[$pk];
    foreach ($data as $k => $v) {
        if ($k == $pk) continue;
        $kkk[] = $k . '=:' . $k;
    }
    $kkk = implode(',', $kkk);
    $stmt = $db->prepare("update $tn set $kkk where $pk=:$pk");
    $stmt->execute($data);
    $stmt->closeCursor();
}

function save1($tn, $data) {
    global $db;
    foreach ($data as $k => $v) {
        $kk[] = $k;
        $vv[] = ':' . $k;
    }
    $kk = implode(',', $kk);
    $vv = implode(',', $vv);
    $stmt = $db->prepare("insert into $tn($kk) values($vv)");
    $stmt->execute($data);
    $stmt->closeCursor();
}


function updates($tn, $data, $w = '1=1') {
    global $db;
    foreach ($data as $k => $v) {
        $kkk[] = $k . '=:' . $k;
    }
    $kkk = implode(',', $kkk);
    $stmt = $db->prepare("update $tn set $kkk where $w");
    $stmt->execute($data);
    $stmt->closeCursor();
}

function updateinc($tn, $f, $n = 1, $w = '1=1') {
    global $db;
    $stmt = $db->prepare("update $tn set $f=$f+$n where $w");
    $stmt->execute();
    $stmt->closeCursor();
}


function query($tn, $f = '*', $w = '1=1', $o = '', $l = '') {
    global $db;
    $stmt = $db->prepare("select $f from $tn where $w $o $l"); //select * from db_admin where id=1 group by id  having
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return $rows;
}

function queryByname($tn, $name, $rname, $f = null) {
    global $db;
    $ff = isset($f) ? $f : '*';
    $stmt = $db->prepare("select $ff from $tn where $name=$rname");
    $stmt->execute([$rname]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return array_shift($rows);
}

function query3($tn, $f = '*', $w = '1=1') {
    global $db;
    $stmt = $db->prepare("select $f from $tn where $w ");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return $rows;
}

function query2($tn, $td, $f = '*', $z = '*', $o = '', $l = '') {
    global $db;
    $stmt = $db->prepare("select d.$f,z.$z from $tn d left outer join $td z on d.$o=z.$l;");

    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
//    echo '<pre>';
//    print_r($rows);
//    die();
    $stmt->closeCursor();
    return $rows;
}

function query2ById($tn, $td, $f = '*', $z = '*', $o = '', $l = '', $id, $did) {
    global $db;
    $stmt = $db->prepare("select d.$f,z.$z from $tn d left outer join $td z on d.$o=z.$l where $id=?;");
    $stmt->execute([$did]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return $rows;
}


function queryById($tn, $id, $f = null) {
    global $db;
    $pk = getpk($tn);
    $ff = isset($f) ? $f : '*';
    $stmt = $db->prepare("select $ff from $tn where $pk=?");
    $stmt->execute([$id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return array_shift($rows);
}


function queryByPid($tn, $pk, $id, $f = null) {
    global $db;
    $ff = isset($f) ? $f : '*';
    $stmt = $db->prepare("select $f from $tn where $pk=?");
    $stmt->execute([$id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    return $rows;
}

function getpk($tn) {
    global $db;
    $stmt = $db->prepare("show full columns from $tn");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $pk = null;
    foreach ($rows as $v) {
        if ($v['Key'] == 'PRI') {
            $pk = $v['Field'];
            break;
        }
    }
    return $pk;
}


function exists($tn, $w) {
    global $db;
    $flag = false;
    if (empty($w)) return $flag;
    $stmt = $db->prepare("select count(*) from $tn where $w");
    $stmt->execute();
    $stmt->bindColumn(1, $c);
    $stmt->fetch(PDO::FETCH_BOUND);
    $stmt->closeCursor();
    if ($c >= 1) $flag = true;
    return $flag;
}

function close() {
    global $db;
    unset($db);
}

function mm($pass, $name = 'root') {
    $ss = $pass . $name;
    $s1 = md5($ss);
    $s2 = sha1($ss);
    $sok = substr($s1, 0, 5) . substr($s2, 0, 5);
    $sok .= substr($s1, 10, 0) . substr($s2, 10, 5);
    $sok .= substr($s1, 20, 5) . substr($s2, 20, 7);
    return $sok;
}

function updateAll($tn, $sorts, $id) {
    global $db;
    $pk = getpk($tn);
    foreach ($sorts as $key => $v) {
        $stmt = $db->prepare("update $tn set sorts='$v' where $pk=$id[$key]");
        $stmt->execute();
    }
    $stmt->closeCursor();
}

//颜色库函数
function color($color = 'rand', $alpha = 0) {
    global $image;
    if (empty($alpha)) {
        $alpha = mt_rand(0, 127);
    }
    switch ($color) {
        case 'red':
            $c = imagecolorallocatealpha($image, 255, 0, 0, $alpha);
            break;
        case 'green':
            $c = imagecolorallocatealpha($image, 0, 255, 0, $alpha);
            break;
        case 'blue':
            $c = imagecolorallocatealpha($image, 0, 0, 255, $alpha);
            break;
        case 'yellow':
            $c = imagecolorallocatealpha($image, 255, 255, 0, $alpha);
            break;
        case 'purple':
            $c = imagecolorallocatealpha($image, 0xff, 0x33, 0xff, $alpha);
            break;
        case 'rand':
            $c = imagecolorallocatealpha($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), $alpha);
            break;
        default:
            $p = '/[0-9,a-f]{6}/i';
            if (preg_match_all($p, $color, $r)) {
                $xx = str_split($r[0][0], 2);
                $c = imagecolorallocatealpha($image, hexdec($xx[0]), hexdec($xx[1]), hexdec($xx[2]), $alpha);
            } else {
                $c = imagecolorallocatealpha($image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), $alpha);
            }
            break;
    }
    return $c;
}

//验证码 字符串截取函数
function sub($len = 1) {
    $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $sss = '';
    for ($i = 0; $i < $len; $i++) {
        $pos = mt_rand(0, strlen($str) - 1);
        $sss .= substr($str, $pos, 1);
    }
    return $sss;
}

//验证码函数
function check($len, $color = 'red', $height = 40) {
    $width = $len * 25;
    global $image;
    $image = imagecreatetruecolor($width, $height);
    imagefill($image, 0, 0, color($color));

    $font = 'hz.ttf';
    for ($i = 0; $i < $len; $i++) {
        $tcolor = color('rand', 50);
        $x = $i * 25 + 2;
        $y = mt_rand(20, 32);
        $size = mt_rand(15, 22);
        $angle = mt_rand(-30, 30);
        $text = sub(1);
        imagettftext($image, $size, $angle, $x, $y, $tcolor, $font, $text);
    }
    for ($i = 0; $i < 10; $i++) {
        $x = mt_rand(0, $width);
        $y = mt_rand(0, $height);
        $text = sub(1);
        $bcolor = color('rand', 120);
        $angle = mt_rand(-30, 30);
        $size = mt_rand(10, 15);
        imagettftext($image, $size, $angle, $x, $y, $bcolor, $font, $text);
    }
    $yy = mt_rand(5, $width);
    $ss = mt_rand(0, $height);
    $white = color('rand', 124);
    $sss = mt_rand(5, 10);
    for ($x = 0; $x < $width; $x++) {
        $y = $yy + $ss * sin($x * M_PI / 100);
        imagefilledellipse($image, $y, $x, $sss, $sss, $white);
        imagefilledellipse($image, $x, $y, $sss, $sss, $white);
    }
    header('content-type:image/jpeg');
    imagejpeg($image);
    imagedestroy($image);
}

//统计文件类型和代码行数 函数
function mycount($path) {
    if (!is_dir($path)) {
        return;
    }
    static $count = ['row' => 0, 'php' => 0, 'jpg' => 0, 'png' => 0, 'gif' => 0, 'other' => 0];
    $arry = array_diff(scandir($path), array('.', '..'));
    foreach ($arry as $file) {
        $files = "$path/$file";
        if (is_dir($files)) {
            mycount($files);
        }
        $ext = pathinfo($files, PATHINFO_EXTENSION);
        switch ($ext) {
            case 'jpg':
            case 'png':
            case 'gif':
                $count[$ext]++;
                break;
            case 'php':
                $count['php']++;
                $count['row'] += count(file($files));
                break;
            default:
                $count['other']++;
                break;
        }
    }
    return $count;

}

//添加水印函数
function text($path, $text = '版权所有', $size = 24, $color = 'red', $pos = 1, $flag = true, $type = '_t') {
    if (is_dir($path)) {
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file) {
            $f = "$path/$file";
            text($f, $size, $text, $color, $pos, $flag, $type);
        }
    } else {
        global $image;
        $image = imagecreatefromstring(file_get_contents($path));
        $w = imagesx($image);
        $h = imagesy($image);
        $angle = 0;
        $font = __DIR__ . '/hz.ttf';
        $fos = imagettfbbox($size, $angle, $font, $text);
        $tw = $fos[2] - $fos[6];
        $th = $fos[3] - $fos[7];
        switch ($pos) {
            case 1:
                $x = 10;
                $y = $th + 10;
                break;
            case 2:
                $x = $w / 2;
                $y = 10;
                break;
            case 3:
                $x = $w - $tw - 10;
                $y = 10;
                break;
            case 4:
                $x = 10;
                $y = ($h - $th) / 2;
                break;
            case 5:
                $x = ($w - $tw) / 2;
                $y = ($h - $th) / 2;
                break;
            case 6:
                $x = ($w - $tw) / 2;
                $y = ($h - $th) / 2;
                break;
            case 7:
                $x = 10;
                $y = $h - 10;
                break;
            case 8:
                $x = ($w - $tw) / 2;
                $y = $h - 10;
                break;
            case 9:
                $x = $w - $tw;
                $y = $h - 10;
            default:
                $x = ($w - $tw) / 2;
                $y = ($h - $th) / 2;
                break;
        }
        imagettftext($image, $size, $angle, $x, $y, color($color), $font, $text);
        if ($flag) {
            imagejpeg($image, $path);
        } else {
            $ext = '.' . pathinfo($path, PATHINFO_EXTENSION);
            $path = str_replace($ext, $type . $ext, $path);
            imagejpeg($image, $path);
        }
        imagedestroy($image);
    }
}

//缩略图函数
function cut($path, $width = 300, $flag = false, $type = '_r', $height = "") {
    if (is_dir($path)) {
        $files = array_diff(scandir($path), array('.', '..'));
        foreach ($files as $file) {
            $img = "$path/$file";
            cut($img, $width, $flag, $type, $height);
        }
    } else {
        $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
        if ($ext == 'jpg' || $ext == 'png') {
            $s = imagecreatefromstring(file_get_contents($path));
            $sw = imagesx($s);
            $sh = imagesy($s);
            if ($width > $sw - 10) {
                return;
            } else {
                if ($height == "") {
                    $height = $width / $sw * $sh;
                } else {
                    $height = $height;
                }
            }
            $i = imagecreatetruecolor($width, $height);
            imagecopyresampled($i, $s, 0, 0, 0, 0, $width, $height, $sw, $sh);
            if ($flag) {
                imagejpeg($i, $path);
            } else {
                $ex = '.' . pathinfo($path, PATHINFO_EXTENSION);
                $path = str_replace($ex, $type . $ex, $path);
                imagejpeg($i, $path);
            }
            imagedestroy($i);
        }
    }
}

//缩略图
function thumbs($i, $path = 'mid', $w = 400, $h = 400) {
    $ii = getimagesize($i);
    if ($ii[0] >= $w) {
        $src = imagecreatefromjpeg($i);
        $sw = $ii[0];
        $sh = $ii[1];

        $h = $h == 0 ? $w / $sw * $sh : $h;
        //建立新的缩略图
        $dst = imagecreatetruecolor($w, $h);
        imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $sw, $sh);
        $new = str_replace('big', $path, $i);
        $dir = pathinfo($new, PATHINFO_DIRNAME);
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }
        imagejpeg($dst, $new);
        imagedestroy($dst);
        imagedestroy($src);
    }
}

//下载文件
function down($dir, $name, $ext, $islogin = false, $ren = 0) {
    if ($islogin) {
        @session_start();
        if (isset($_SESSION['member'])) {
        } else {
            exit("此资源，必须是会员才可以下载");
            return;
        }
    }
    $file = $dir . './' . $name . $ext;
    if (file_exists($file)) {
        $f = fopen($file, 'r');
        $len = filesize($file);
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Accept-Length:" . $len);
        switch ($ren) {
            case 1:
                $name = date('YmdHis');
                break;
            case 2:
                $name = uniqid();
                break;
            case 3:
                $name = uuid();
                break;
        }
        header("Content-Disposition:attachment;filename=" . $name . $ext);
        $buf = 1024;
        $count = 0;
        while (!feof($f) && $count < $len) {
            $r = fread($f, $buf);
            $count += $buf;
            echo $r;
        }
        fclose($f);
        return;
    } else {
        exit("未知资源，无法下载！！！");
        return;
    }
}

//文件上传
function upload($dir = './', $rename = 1, $size = 20, $allow = ['gif', 'jpg', 'png', 'rar', 'zip', 'pdf']) {
    $size = $size * 1048576;
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }
    $files = [];
    if (!empty($_FILES)) {
        foreach ($_FILES as $fs) {
            if (is_array($fs['name'])) {
                foreach ($fs['tmp_name'] as $k => $f) {
                    $ext = strtolower(pathinfo($fs['name'][$k], PATHINFO_EXTENSION));
                    if (in_array($ext, $allow) && $fs['size'][$k] <= $size) {
                        $name = ren($dir, $fs['name'][$k], $rename);
                        if (move_uploaded_file($f, $dir . '/' . $name)) {
                            $files[] = $name;
                        }
                    }
                }
            } else {
                $ext = strtolower(pathinfo($fs['name'], PATHINFO_EXTENSION));
                if (in_array($ext, $allow) && $fs['size'] <= $size) {
                    $name = ren($dir, $fs['name'], $rename);
                    if (move_uploaded_file($fs['tmp_name'], $dir . './' . $name)) {
                        $files[] = $name;
                    }
                }
            }
        }
        return $files;
    }
    return false;
}

function ren($dir, $name, $rename) {
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $nname = $name;
    switch ($rename) {
        case 1:
            $nname = date('YmdHis') . '_' . sprintf('%05d', mt_rand(0, 99999)) . '.' . $ext;
            break;
        case 2:
            $nname = uniqid() . '.' . $ext;
            break;
        case 3:
            $nname = uuid() . '.' . $ext;
            break;
        case 4:
            $num = 0;
            while (file_exists($dir . '/' . $nname)) {
                $num++;
                $nname = pathinfo($name, PATHINFO_FILENAME) . '(' . $num . ').' . $ext;
            }
            break;
    }
    return $nname;
}

//全球唯一ID UUID
function uuid($namespace = '') {
    static $guid = '';
    $uid = uniqid("", true);
    $data = $namespace;
    $data .= $_SERVER['REQUEST_TIME'];
    $data .= $_SERVER['HTTP_USER_AGENT'];
    $data .= $_SERVER['LOCAL_ADDR'];
    $data .= $_SERVER['SERVER_PORT'];
    $data .= $_SERVER['LOCAL_ADDR'];
    $data .= $_SERVER['SERVER_PORT'];
    $hash = strtolower(hash('ripemd128', $uid . $guid . md5($data)));
    $guid = substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
    return strtolower($guid);
}


function logo($img, $pos = 5) {
    $i = imagecreatefromstring(file_get_contents($img));
    $w = imagesx($i);
    $h = imagesy($i);

    $logo = imagecreatefromstring(file_get_contents(dirname(__FILE__) . '/logo.png'));
    $lw = imagesx($logo);
    $lh = imagesy($logo);
    switch ($pos) {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        case 4:
            break;
        case 5:
            $x = ($w - $lw) / 2;
            $y = ($h - $lh) / 2;
            break;
        case 6:
            break;
        case 7:
            break;
        case 8:
            break;
        case 9:
            $x = $w - $lw - 10;
            $y = $h - $lh - 10;
            break;
        default:
            break;
    }
    imagecopy($i, $logo, $x, $y, 0, 0, $lw, $lh);
    imagejpeg($i, $img);
    imagedestroy($i);
    imagedestroy($logo);
}

function clears($content, $keywords) {
    $contents = preg_replace('/style=".*"/U', '', $content);
    //$contents=preg_replace('/</[^aa/>]+>/U','',$content);
    $content1 = preg_replace("/<[img|IMG].*?src=[\\' | \"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\\'|\"].*?[\/]?>/", '', $contents);
    $content2 = preg_replace('/&nbsp;/U', '', $content1);
    $content3 = preg_replace('/<a[^>]*>(.*)<\/a>/isU', '\\1', $content2);
    $content4 = preg_replace('/(' . $keywords . ')/', '<span style="color:red">$1</span>', $content3);
    echo $content4;
}

function highlight($content, $keywords) {

    $content4 = preg_replace('/(' . $keywords . ')/', '<span style="color:red">$1</span>', $content);
    echo $content4;
}


////上下篇
function pianDiv($tn, $titlefild, $cp, $andw = '', $key = 'id', $tnpre = '') {
    global $db;
    $tn = $tnpre . $tn;
    $pk = getPK($tn);
    //获取上一篇
    $psql = $db->prepare("select * from $tn where $pk < $cp $andw order by $pk desc limit 1");
    $psql->execute();
    $pp = $psql->fetchAll(PDO::FETCH_ASSOC);
    $perr = $psql->errorInfo()[2];
    $psql->closeCursor();
    //获取下一篇
    $nsql = $db->prepare("select * from $tn where $pk > $cp $andw limit 1");
    $nsql->execute();
    $np = $nsql->fetchAll(PDO::FETCH_ASSOC);
    $nerr = $nsql->errorInfo()[2];
    $nsql->closeCursor();
    //调试信息
    //拼装div
    $str = '<div class=\'xx\'">';
    if (empty($pp)) {
        $str .= sprintf('<span>上一篇：没有了</span>');
    } else {
        $str .= sprintf('<a href="?%s=%d" class="up">上一篇：%s</a>', $key, $pp[0][$pk], $pp[0][$titlefild]);
    }
    $str .= '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
    if (empty($np)) {
        $str .= sprintf('<span>下一篇：没有了</span>');
    } else {
        $str .= sprintf('<a href="?%s=%d" class="down">下一篇：%s</a>', $key, $np[0][$pk], $np[0][$titlefild]);
    }
    $str .= '</div>';
    return $str;
}